/*
* Copyright (C) Microsoft. All rights reserved.  
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not 
* use this file except in compliance with the License.  You may obtain a copy 
* of the License at http://www.apache.org/licenses/LICENSE-2.0  
* 
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 
* WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
* MERCHANTABLITY OR NON-INFRINGEMENT. 
*
* See the Apache License, Version 2.0 for specific language governing 
* permissions and limitations under the License.
*
*/
#pragma once

#include <baja/common.hpp>
#include <windows.h>
#include <ObjIdl.h>

namespace baja { namespace win32 { namespace details {

// NOTE: supports a single COM interface, with variadic templates I think we could support more in the future...
// or do some complicated tricks like ncom.h
template <class TInterface>
class com_base : public TInterface
{
private:

    volatile LONG _refCount;

public:
    com_base() : _refCount(0) {}
    virtual ~com_base() {}

        // IUnknown

    HRESULT __stdcall QueryInterface(const IID &iid, void **ppv)
    {
        if (ppv == NULL)
        {
            return E_POINTER;
        }

        *ppv = NULL;

        if (IID_IUnknown == iid)
        {
            *ppv = static_cast<IUnknown*>(this);
        }
        else
        {
            this->internalQueryInterface(iid, ppv);
            if (!*ppv) 
                return E_NOINTERFACE;
        }
    
        this->AddRef();
            
        return S_OK;
    }

    ULONG __stdcall AddRef()
    {
        return ::InterlockedIncrement(&_refCount);
    }

    ULONG __stdcall Release()
    {
        ULONG refCount = ::InterlockedDecrement(&_refCount);
        if (0L == refCount)
        {
            delete this;
        }

        return refCount;
    }

protected:

    virtual void internalQueryInterface(const IID& iid, void** ppv) = 0;

};

}}} // namespace baja::win32::details